package com.qdlc.p2p.biz.web.filter;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import com.alibaba.fastjson.JSON;
import com.qdlc.p2p.common.util.PropertiesUtil;
import com.qdlc.p2p.common.util.StringUtil;
import com.qdlc.p2p.common.util.code.MD5;

/**
 * APP接口过滤器
 * @author xxx
 * @version 2.0
 * @date 2015年6月4日 下午8:09:02
 */
public class AppInterfaceFilter implements Filter {
	
	public void init(FilterConfig filterConfig) throws ServletException {

    }
    
    public void destroy() {

    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    	boolean allow = false;
    	String app_secret = PropertiesUtil.getValue("app_secret");
    	//String app_key = PropertiesUtil.getValue("app_key");
    	// 校验参数有效性(参数合理性校验、signa校验)
    	String appKey = request.getParameter("appkey");
    	String signa = request.getParameter("signa");
		String ts = request.getParameter("ts");
		
		String signa_ = MD5.encryption((MD5.encryption(app_secret + ts) + appKey )).toUpperCase();
		if ( StringUtil.isNotBlank(appKey) && StringUtil.isNotBlank(signa) && StringUtil.isNotBlank(ts)  && signa_.equals(signa) ) {
			allow = true;
		}
    	// 根据参数校验结果，准许请求 或 返回不准许访问的提示
    	if(!allow){
    		Map<String, Object> data = new HashMap<String, Object>();
    		data.put("resCode", "8");
			data.put("resMsg", PropertiesUtil.getValue("签名有误!"));
    		response.setContentType("application/json;charset=UTF-8");
    		PrintWriter out = response.getWriter();
    		out.print(JSON.toJSONString(data));
    		out.flush();
    		out.close();
    	} else {//准许请求
    		chain.doFilter(request, response);
    	}
    }
}